#include "Drv_FPGA_SPI.h"
#include "BitBand.h"


#define PIN_SCL        (PFout(7))
#define PIN_MOSI       (PFout(1))
#define PIN_MISO       (PEin(6))
#define PIN_CS_CMD     (PFout(5))
#define PIN_CS_DATA    (PFout(3))

#define FPGA_SPI_SCL(x)       PIN_SCL = (x)
#define FPGA_SPI_MOSI(x)      PIN_MOSI = (x)
#define FPGA_SPI_MISO()       PIN_MISO
#define FPGA_SPI_CS_CMD(x)    PIN_CS_CMD = (x)
#define FPGA_SPI_CS_DATA(x)   PIN_CS_DATA = (x)


void FPGA_SPI_Send_Cmd(uint8_t cmd)
{
  uint32_t i;

  FPGA_SPI_CS_CMD(0);
  for(i = 0; i < 8; ++i)
  {
    FPGA_SPI_MOSI((cmd &(0x80)) ?1 :0);
    cmd <<= 1;
    FPGA_SPI_SCL(0);
    FPGA_SPI_SCL(1);
  }
  FPGA_SPI_CS_CMD(1);
}

void FPGA_SPI_Send_Data(uint32_t data)
{
  uint32_t i;

  FPGA_SPI_CS_DATA(0);
  for(i = 0; i < 32; ++i)
  {
    FPGA_SPI_MOSI((data &(0x80000000)) ?1 :0);
    data <<= 1;
    FPGA_SPI_SCL(0);
    FPGA_SPI_SCL(1);
  }
  FPGA_SPI_CS_DATA(1);
}

uint32_t FPGA_SPI_Rece_Data(void)
{
  uint32_t i;
  uint32_t buf_data = 0;

  FPGA_SPI_CS_DATA(0);
  for( i = 0; i < 32; ++i)
  {
    FPGA_SPI_SCL(1);
    FPGA_SPI_SCL(0);
    buf_data <<= 1;
    buf_data = buf_data | (FPGA_SPI_MISO());
  }
  FPGA_SPI_CS_DATA(1);

  return  buf_data;
}

void FPGA_SPI_Send(uint8_t cmd, uint32_t data)
{
  FPGA_SPI_Send_Cmd(cmd);
  FPGA_SPI_Send_Data(data);
}

uint32_t FPGA_SPI_Rece(uint8_t cmd)
{
  FPGA_SPI_Send_Cmd(cmd);
  return (FPGA_SPI_Rece_Data());
}
